// db.ts
import { openDB } from "idb";
import type { DBSchema, IDBPDatabase } from "idb";
import type { ChatHistoryList } from "@/types";

const DB_NAME = "chat-app";
const STORE_NAME = "chatSessions";

interface MyDB extends DBSchema {
  chatSessions: {
    key: string;
    value: ChatHistoryList;
  };
}

let dbInstance: IDBPDatabase<MyDB> | null = null;
export async function getDB(): Promise<IDBPDatabase<MyDB>> {
  if (!dbInstance) {
    dbInstance = await openDB<MyDB>(DB_NAME, 1, {
      upgrade(db) {
        if (!db.objectStoreNames.contains(STORE_NAME)) {
          db.createObjectStore(STORE_NAME, { keyPath: "id" });
        }
      },
    });
  }
  return dbInstance;
}

export async function saveSession(session: ChatHistoryList): Promise<void> {
  console.log("Saving session:", session);
  // 转换响应式对象为普通对象 深拷贝
  const plainSession = JSON.parse(JSON.stringify(session));
  const db = await getDB();
  await db.put(STORE_NAME, plainSession);
}

export async function getSession(
  id: string
): Promise<ChatHistoryList | undefined> {
  const db = await getDB();
  return await db.get(STORE_NAME, id);
}

export async function deleteSession(id: string): Promise<void> {
  const db = await getDB();
  await db.delete(STORE_NAME, id);
}

export async function getAllSessions(): Promise<ChatHistoryList[]> {
  const db = await getDB();
  return await db.getAll(STORE_NAME);
}
